package top.ply.authservice.service.impl;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import top.ply.authservice.service.AuthService;
import top.ply.common_unit.token.JWTUtil;

import java.util.Map;

@Service("baseAuthService")
@RefreshScope
public abstract class BaseAuthService implements AuthService {

    @Value("${authservice.token.secretKey}")
    String authServiceSecretKey;

    @Value("${authservice.token.expireTime}")
    long authServiceTokenExpireTime;

    public String generateToken(Map<String, String> payload) {
        return JWTUtil.createToken(payload, authServiceSecretKey, authServiceTokenExpireTime);
    }

    @Override
    public boolean verifyToken(String token) {
        return !JWTUtil.isExpire(token, authServiceSecretKey);
    }

    @Override
    public String refreshToken(String token) {
        if (!verifyToken(token)) {
            return null;
        } else {
            Map<String, String> payload = JWTUtil.getPayload(token, authServiceSecretKey);
            return JWTUtil.createToken(payload, authServiceSecretKey, authServiceTokenExpireTime);
        }
    }

    /**
     * 以关键字，生成唯一用户ID，使用当前时间戳+keyword MD5 之后产生的id为用户id
     * @param keyword 用户id关键字
     * @return 全局唯一ID
     */
    final String generateUserID(String keyword) {
        long l = System.currentTimeMillis();
        String original = l + keyword;
        String userID = DigestUtils.md5DigestAsHex(original.getBytes());
        while (isExists(userID)) {
            l = System.currentTimeMillis();
            original = l + keyword;
            userID = DigestUtils.md5DigestAsHex(original.getBytes());
        }
        return userID;
    }

     abstract boolean isExists(String userID);
}
